<template>
  <div class="caseimgmain beautifulScroll">
    <div class="caseimgbox" ref="caseimgbox">
      <div class="caseback" @click="goback"><van-icon name="arrow-left" /></div>
      <div class="casepages"
        ><span>{{ findindex() + 1 }}/{{ imgsrc.length }}</span></div
      >
      <div class="casedt" @click="stopProcessing" v-if="processImagesflag">
        <img src="@/assets/images/blzt.png" alt="" /> 暂停播放</div
      >
      <div class="casedt" @click="processImages" v-else>
        <img src="@/assets/images/blbf.png" alt="" />
        动态播放
      </div>

      <canvas
        id="myCanvaslxh"
        :width="hbwidth"
        :height="hbheight"
        ref="canvasRef"
      ></canvas>
    </div>
    <div
      class="caseimglbox beautifulScroll"
      ref="caseimglbox"
      @scroll="onScroll"
    >
      <!-- 显示最多6个元素 -->
      <div
        v-for="(item, index) in imgsrc"
        :key="index"
        class="caseimgitem"
        @click="tagdcom(item.caseImgId)"
      >
        <img :src="`${base + item.imgUrl}`" />
        <div class="msx" v-if="item.caseImgId == dcomid"></div>
      </div>
    </div>
    <!-- 底部改沟 -->
    <div class="caseimgdesmain beautifulScroll">
      <div class="caseimgdesments beautifulScroll">
        <div
          class="caseimgmentitem"
          :class="mentname == item.id ? 'caseimgmentitemac' : ''"
          v-for="item in ment"
          @click="mentname = item.id"
          >{{ item.name }}</div
        >
      </div>
      <div class="caseimgdesboxs" v-if="mentname == 3">
        <div class="caseimgdest"
          >讨论{{ discussListdata.length }}
          <span @click="scrollToBottom">最新</span>
        </div>
        <div class="caseimgdeslist beautifulScroll" ref="caseImgDesList">
          <div class="caseimgdeslistitem" v-for="item in discussListdata">
            <div class="caseimguser">
              <img src="@/assets/images/1.png" alt="" />
            </div>
            <div class="caseimglistright">
              <div class="casestu">{{ item.studentName }}</div>
              <div class="casecont">{{ item.content }}</div>
              <div class="casetimed">{{ item.createTime }}</div>
            </div>
          </div>
        </div>
        <div class="caseimgent">
          <div class="caseimguser">
            <img src="@/assets/images/1.png" alt="" />
          </div>
          <div class="caseimginput"
            ><input type="text" placeholder="说些什么" v-model="content"
          /></div>
          <div class="caseimgfs" @click="discussAddfn">
            <van-icon name="guide-o" />
          </div>
        </div>
      </div>
      <div class="caseimgdesbox" v-if="mentname == 1">{{ situation }}</div>
      <div class="caseimgdesbox" v-if="mentname == 2">{{ imgFeatures }}</div>
      <div class="caseimgdesbox" v-if="mentname == 4">{{
        diagnosticConclusion
      }}</div>
    </div>
    <!--  -->
  </div>
</template>

<script lang="ts" setup>
  import {
    nextTick,
    onBeforeUnmount,
    onMounted,
    onUnmounted,
    reactive,
    ref,
  } from 'vue';
  const emit = defineEmits<{
    (event: 'goback'): void;
    (event: 'customEvent', payload: any): void; // 定义自定义事件
  }>();
  import { discussList, discussAdd, caserecordAdd } from '@/api/case';
  import { storeToRefs } from 'pinia';
  import { useUserStore } from '@/store';
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  const studentId = ref(userdata.studentId.value);
  //   最新
  const caseImgDesList = ref();
  // 点击最新时滚动到最底部
  const scrollToBottom = () => {
    nextTick(() => {
      const listElement = caseImgDesList.value as HTMLElement;
      if (listElement) {
        listElement.scrollTop = listElement.scrollHeight;
      }
    });
  };
  // 发送讨论
  const content = ref('');
  const discussAddfn = () => {
    discussAdd({
      studentId: studentId.value,
      caseId: caseId.value,
      content: content.value,
    }).then((res: any) => {
      if (res.code == 200) {
        freach();
        content.value = '';
      } else {
      }
    });
  };
  // 获取病例讨论
  const discussListdata = ref([]);
  const freach = () => {
    discussList({ caseId: caseId.value }).then((res: any) => {
      if (res.code == 200) {
        console.log('查询成功', res.data);
        discussListdata.value = res.data.list;
      } else {
      }
    });
  };
  // 获取完成
  const goback = () => {
    emit('goback');
  };
  const props = defineProps<{
    imgsrc: string[];
    situation: '';
    imgFeatures: '';
    diagnosticConclusion: '';
    caseId: '';
  }>();
  const imgsrc = ref();
  imgsrc.value = props.imgsrc;
  const dcomid = ref('10');
  dcomid.value = imgsrc.value[0].caseImgId;
  const situation = ref();
  situation.value = props.situation;
  const imgFeatures = ref();
  imgFeatures.value = props.imgFeatures;
  const diagnosticConclusion = ref();
  diagnosticConclusion.value = props.diagnosticConclusion;
  const caseId = ref();
  caseId.value = props.caseId;
  freach();
  //   定义数据
  const mentname = ref(1);
  const ment = ref([
    {
      id: 1,
      name: '患者情况',
    },
    {
      id: 2,
      name: '影像表现',
    },
    {
      id: 3,
      name: '病例讨论',
    },
    {
      id: 4,
      name: '诊断结论',
    },
  ]);

  // 定义画布高低
  const hbwidth = ref();
  const hbheight = ref();
  /// 引用 DOM 元素
  const caseimgbox = ref<HTMLDivElement | null>(null);
  const canvasRef = ref<HTMLCanvasElement | null>(null);
  // 状态数据
  const state = reactive({
    img: new Image(),
    imgWidth: 389,
    imgHeight: 200,
    ctx: null as CanvasRenderingContext2D | null,
  });
  const base = ref((window as any).config.VUE_APP_IMG_API);

  // 初始化
  onMounted(() => {
    // 设置 canvas 尺寸

    hbwidth.value = caseimgbox.value?.offsetWidth;
    hbheight.value = caseimgbox.value?.offsetHeight;

    const canvas = canvasRef.value!;
    console.log(canvasRef.value);

    canvas.width = hbwidth.value;
    canvas.height = hbheight.value;

    // 获取 canvas 上下文
    state.ctx = canvas.getContext('2d');

    // 加载图片
    state.img.src = base.value + imgsrc.value[0].imgUrl;
    state.img.onload = () => {
      state.imgWidth = state.img.naturalWidth;
      state.imgHeight = state.img.naturalHeight;
      draw(); // 图片加载完成后绘制
    };

    if (canvasRef.value) {
      canvasRef.value.addEventListener('touchstart', handleTouchStart);
      canvasRef.value.addEventListener('touchend', handleTouchEnd);
    }
  });
  // 取消事件监听
  onBeforeUnmount(() => {
    const caseimglboxElement = canvasRef.value;
    if (caseimglboxElement) {
      caseimglboxElement.removeEventListener('touchstart', handleTouchStart);
      caseimglboxElement.removeEventListener('touchend', handleTouchEnd);
    }
  });
  const findindex = () => {
    if (imgsrc.value.length < 0) {
      return;
    }
    return imgsrc.value.findIndex(
      (item: any) => item.caseImgId == dcomid.value
    );
  };
  // 绘制函数
  const draw = () => {
    const canvas = canvasRef.value!;
    const ctx = state.ctx!;
    const img = state.img;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 设置缩放比例，这里设为 90% 的缩小比例
    const scale = 0.5;

    // 计算缩放后的宽度和高度
    const scaledWidth = img.naturalWidth * scale;
    const scaledHeight = img.naturalHeight * scale;

    // 计算居中绘制的偏移量
    const xOffset = (canvas.width - scaledWidth) / 2;
    const yOffset = (canvas.height - scaledHeight) / 2;

    // 绘制图片
    ctx.drawImage(img, xOffset, yOffset, scaledWidth, scaledHeight);
  };

  const tagdcoms = (i: any) => {
    const index = imgsrc.value.findIndex(
      (item: any) => item.caseImgId == dcomid.value
    );
    if (i == 1) {
      if (imgsrc.value[index + 1]) {
        dcomid.value = imgsrc.value[index + 1].caseImgId;
        tagdcom(dcomid.value);
        draw();
      }
    } else {
      if (imgsrc.value[index - 1]) {
        dcomid.value = imgsrc.value[index - 1].caseImgId;
        tagdcom(dcomid.value);
        draw();
      }
    }
  };

  const tagdcom = (i: any) => {
    console.log('当前图像id', i);
    const imgsrcd = imgsrc.value.find((item: any) => item.caseImgId == i);

    dcomid.value = i;
    state.img.src = base.value + imgsrcd.imgUrl;
    state.img.onload = () => {
      state.imgWidth = state.img.width;
      state.imgHeight = state.img.height;
    };

    // }
    draw();
  };

  let timeoutId: NodeJS.Timeout | null = null; // 存储定时器ID

  const processImagesflag = ref(false); // 控制是否继续执行的标志

  const processImages = () => {
    processImagesflag.value = true;
    // 使用 findIndex 查找匹配的元素，并获取其索引
    const targetIndex = imgsrc.value.findIndex(
      (src) => src.caseImgId === dcomid.value
    );

    // 如果找到了匹配的元素
    if (targetIndex !== -1 && processImagesflag.value) {
      // 从找到的索引开始，执行后续操作
      const processNext = (index: number) => {
        // 如果 processImagesflag 为 false，则停止继续执行
        if (!processImagesflag.value) {
          if (timeoutId) {
            clearTimeout(timeoutId); // 清空计时器
          }
          return; // 停止执行
        }

        // 如果当前索引在数组中有效
        if (index < imgsrc.value.length) {
          const src = imgsrc.value[index];

          // 判断当前的 index 是否符合特殊条件 7, 14, 21 等
          const isSpecialIndex = (index + 1) % 7 === 0;

          // 如果符合特殊条件，调用 toggleAutoScroll
          if (isSpecialIndex) {
            toggleAutoScroll();
          }

          // 执行 tagdcom
          tagdcom(src.caseImgId);

          // 延迟 1 秒后执行下一个循环
          timeoutId = setTimeout(() => {
            processNext(index + 1);
          }, 1000); // 1000 毫秒 = 1 秒
          // 如果索引已经到达数组的最后一个元素，设置 isProcessingComplete 为 true
          if (index === imgsrc.value.length - 1) {
            processImagesflag.value = false;
          }
        }
      };

      // 开始从找到的索引处执行
      processNext(targetIndex);
    }
  };

  // 停止处理函数
  const stopProcessing = () => {
    processImagesflag.value = false; // 设置为 false 停止循环
    if (timeoutId) {
      clearTimeout(timeoutId); // 清空定时器
    }
  };

  // 监听变量
  const startX = ref(0); // 触摸起始点
  const endX = ref(0); // 触摸结束点

  // 监听触摸开始事件
  const handleTouchStart = (e: TouchEvent) => {
    console.log('开始触摸');

    startX.value = e.touches[0].clientX; // 获取触摸开始时的 X 坐标
  };

  // 监听触摸结束事件
  const handleTouchEnd = (e: TouchEvent) => {
    console.log('结束触摸');
    endX.value = e.changedTouches[0].clientX; // 获取触摸结束时的 X 坐标
    // 判断滑动方向
    if (startX.value > endX.value) {
      // 向左滑动
      tagdcoms(-1); // 执行向左滑动操作
    } else if (startX.value < endX.value) {
      // 向右滑动
      tagdcoms(1); // 执行向右滑动操作
    }
  };
  //   开始处理图像加载方法

  // 图像加载处理完成
  const caseimglbox = ref<HTMLElement | null>(null);

  const isAutoScrolling = ref(false); // 自动滚动标志
  const intervalId = ref<number | null>(null); // 存储定时器的 ID

  // 获取每个元素的宽度
  const getItemWidth = () => {
    const container = caseimglbox.value;
    const item = container?.querySelector('.caseimgitem');
    return item ? item.clientWidth : 0;
  };

  // 滚动到容器下一个 6 个元素
  const scrollToNext = () => {
    const container = caseimglbox.value;
    if (container) {
      const itemWidth = getItemWidth();
      const scrollWidth = itemWidth * 6; // 每次滚动 6 个元素的宽度
      container.scrollLeft += scrollWidth + 65; // 每次滚动 6 个元素的宽度
    }
  };

  // 启动自动滚动
  const startAutoScroll = () => {
    if (isAutoScrolling.value) return; // 防止多次启动
    isAutoScrolling.value = true;
    scrollToNext();
    // intervalId.value = setInterval(() => {
    //   scrollToNext();
    // }, 2000); // 每2秒滚动一次
  };

  // 停止自动滚动
  const stopAutoScroll = () => {
    if (intervalId.value) clearInterval(intervalId.value);
    intervalId.value = null;
    isAutoScrolling.value = false;
  };

  // 切换自动滚动状态
  const toggleAutoScroll = () => {
    if (isAutoScrolling.value) {
      stopAutoScroll();
    } else {
      startAutoScroll();
    }
  };

  // 监听滚动事件，暂停自动滚动
  const onScroll = () => {
    // 手动滚动时暂停自动滚动
    if (
      caseimglbox.value &&
      caseimglbox.value.scrollLeft <
        caseimglbox.value.scrollWidth - caseimglbox.value.clientWidth
    ) {
      stopAutoScroll(); // 手动滚动时暂停自动滚动
    }
  };

  // showDialog
  import { showDialog } from 'vant';

  const showms = () => {
    if (topfalg.value) {
      showDialog({
        message: '当前页面竖屏体验更佳！',
        theme: 'round-button',
      }).then(() => {
        // on close
      });
    }
  };
  const mediaQuery = ref(null);
  const topfalg = ref(false);

  const handleOrientationChange = (event) => {
    console.log(event.matches ? '横屏' : '竖屏');
    topfalg.value = event.matches;
    showms();
  };

  onMounted(() => {
    mediaQuery.value = window.matchMedia('(orientation: landscape)');
    topfalg.value = mediaQuery.value.matches;

    mediaQuery.value.addEventListener('change', handleOrientationChange);

    showms();
  });

  onUnmounted(() => {
    if (mediaQuery.value) {
      mediaQuery.value.removeEventListener('change', handleOrientationChange);
    }
  });
</script>

<style scoped>
  .caseimgmain {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
  }

  .caseimgbox {
    width: 100%;
    /* height: 500px; */
    height: 40%;
    background: #000000;
    border-radius: 0px 0px 0px 0px;
    position: relative;
  }

  .caseimglbox {
    display: flex;
    flex-wrap: nowrap; /* 不允许换行 */
    width: 750px; /* 确保容器宽度只能显示 6 个元素 */
    /* height: 140px; */
    height: 10%;
    overflow-x: auto; /* 水平滚动 */
    background: #4b4d52;
    padding: 8px 10px;
    -webkit-overflow-scrolling: touch; /* 支持移动端的平滑滚动 */
  }

  .caseimgitem {
    padding: 0;
    background-color: #fff;
    margin: 0px 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0; /* 防止元素缩小 */
    position: relative;
  }
  .caseback {
    font-size: 36px;
    color: #ffff;
    position: absolute;
    left: 20px;
    top: 20px;
  }
  .caseimgitem img {
    width: 100%;
    height: 100%;
  }
  .msx {
    position: absolute;
    width: 100%;
    height: 100%;
    border: 2px solid #fff;
    left: 1px;
    top: 1px;
  }
  .casedt {
    display: flex;
    flex-direction: column;
    font-size: 20px;
    color: #fff;
    position: absolute;
    bottom: 15px;
    right: 20px;
    z-index: 9999;
    align-items: center;
  }
  .casedt img {
    width: 54px;
    height: 54px;
  }
  .casepages {
    padding: 10px 20px;
    height: 48px;
    background: rgba(56, 53, 53, 0.9);
    border-radius: 8px 8px 8px 8px;
    font-size: 24px;
    color: #fff;
    position: absolute;
    right: 15px;
    top: 15px;
  }
  .caseimgdesmain {
    display: flex;
    width: 100%;
    height: 50%;
    overflow-y: auto;
  }
  .caseimgdesments {
    padding: 10px;
    width: 165px;
    height: 100%;
    background-color: #eef1f4;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow-y: auto;
  }
  .caseimgdesbox {
    width: 585px;
    max-height: 100%;
    background: #ffffff;
    padding: 20px;
    font-size: 28px;
    line-height: 40px;
  }
  .caseimgmentitem {
    width: 131px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px 10px 10px 10px;
    font-size: 26px;
    color: #666666;
    margin: 20px 0;
  }
  .caseimgmentitemac {
    color: #fff;
    background: #5f6d7c;
  }
  .caseimgdesboxs {
    width: 585px;
    max-height: 100%;
    background: #ffffff;
    padding: 20px;
    font-size: 28px;
    display: flex;

    align-items: center;
    flex-direction: column;
  }
  .caseimgdest {
    border-bottom: 1px solid #aaaaaa;
    height: 65px;
    width: 538px;
    display: flex;
    align-items: center;
    font-size: 26px;
    color: #666666;
  }
  .caseimgent {
    width: 532px;
    height: 85px;
    background: #eef1f4;
    border-radius: 10px 10px 10px 10px;
    display: flex;
    align-items: center;
    padding: 0px 10px;
    position: absolute;
    bottom: 20px;
  }
  .caseimguser {
    height: 52px;
    width: 52px;
    border-radius: 50%;
  }
  .caseimguser img {
    height: 52px;
    width: 52px;
  }
  .caseimginput {
    width: 390px;
    height: 50px;
    overflow: hidden;
    margin: 0px 10px;
  }
  .caseimginput input {
    width: 390px;
    height: 50px;
    background-color: #eef1f4;
  }
  .caseimgfs {
    font-size: 40px;
  }
  .caseimgdeslist {
    overflow-y: scroll;
    width: 100%;

    display: flex;
    flex-direction: column;
    padding-bottom: 100px;
  }
  .caseimgdeslistitem {
    display: flex;
    margin: 10px 0;
    align-items: center;
  }
  .caseimglistright {
    display: flex;
    flex-direction: column;
    margin: 0px 10px;
  }
  .casestu {
    font-size: 26px;
    color: #666666;
  }
  .casecont {
    width: 466px; /* 设置固定宽度 */
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏超出容器的部分 */
    text-overflow: ellipsis; /* 当文本超出时显示省略号 */
    font-size: 24px;
    margin: 5px 0;
  }
  .casetimed {
    font-size: 18px;
    color: #666666;
  }
  .caseimgdest span {
    color: #434e74;
    font-size: 26px;
    margin-left: 20px;
    display: block;
  }
</style>
